﻿using UnityEngine;
using System.Collections;

public class EnemyState : MonoBehaviour {

	float currentHelath = 2.0f;

	public ParticleEmitter damageEffect = null;
	public float damageEffectHeight = 1.0f;
	public float damageEffectRadiusOffset = 0.11f;

	public GameObject explosionEffect = null;


	public void Damage(Transform towerTransform, float fireActiveTime, float attackPower){
		currentHelath -= attackPower;
		if (currentHelath > 0.0f) { // I'm alive!!!!
			if (damageEffect == null) return;
			StartCoroutine (DamageEffectProcess (towerTransform, fireActiveTime));
		} else {
			GameObject explosionObject = Instantiate(explosionEffect) as GameObject;
			explosionObject.transform.position = transform.position + (Vector3.up * damageEffectHeight);

			Destroy(gameObject);
		}
	}

	IEnumerator DamageEffectProcess(Transform towerTransform, float fireActiveTime){
		damageEffect.emit = true;
		float deltaTime = 0.0f;
		while ( towerTransform != null && (deltaTime < fireActiveTime)) {
			deltaTime += Time.deltaTime;
			Vector3 dir = towerTransform.position - transform.position; // get direction
			dir.y = 0.0f;
			dir.Normalize();
			damageEffect.transform.position = transform.position + 
				(Vector3.up * damageEffectHeight) + damageEffectRadiusOffset * dir;
			yield return new WaitForEndOfFrame();
		}
		damageEffect.emit = false;
		yield return null;
	}
}
